extern crate clap;

use clap::{Arg, App};
use std::path::Path;
use std::process;
use std::fs::File;
use std::io::{Read, Write};

fn main() {
    let matches = App::new("tcat")
        .version("0.1.0")
        .author("tangjz <36634584@qq.com>")
        .about("a drop in cat replacement written in Ruest")
        .arg(Arg::with_name("FILE")
            .help("File to print.")
            .empty_values(false)
        )
        .get_matches();

    if let Some(file) = matches.value_of("FILE") {
        println!("Value of file argument: {}", file);
        if Path::new(&file).exists() {
            /*println!("File exists!!");
            let mut f = File::open(file).expect("[tcat Error] File not found.");
            let mut data = String::new();
            f.read_to_string(&mut data).expect("[tcat Error] Unable to read the file.");
            println!("{}", data);*/
            match File::open(file) {
                Ok(mut f) => {
                    let mut data = String::new();
                    f.read_to_string(&mut data).expect("[tcat Error] Unable to read the file.");
                    let stdout = std::io::stdout();
                    let mut handle = std::io::BufWriter::new(stdout);
                    match writeln!(handle, "{}", data) {
                        Ok(_res) => {},
                        Err(err) => {
                            eprintln!("[tcat Error] Unable to display the file contents. {:?}", err);
                            process::exit(1);
                        }
                    }
                },
                Err(err) => {
                    eprintln!("[tcat] Error Unable to read the file. {:?}", err);
                    process::exit(1);
                },
            }
        } else {
            eprintln!("[tcat Error] No such file or directory.");
            process::exit(1);
        }
    }
}
